<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Encapsulates a query for tags.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMTagQuery extends DMAbstractSocialDataQuery implements DMDataStoreQuery,
		DMURIAddressable {

	const DEFAULT_LIMIT = 50;

	/** @var boolean */
	private $sort_by_frequency;

	/**
	 * Alias of getSearchResultsAsObjects().
	 * 
	 * @return Array of DMTag objects
	 */
	public function getSearchResults() {
		return $this->getSearchResultsAsObjects();
	}

	/**
	 * @return Associative array of tag value => count pairs
	 */
	public function getSearchResultsAsCounts() {
		$this->setNumResults(
				$this->getDataStore()->getTagsForQueryAsCounts($this, true));
		return $this->getDataStore()->getTagsForQueryAsCounts($this, false);
	}

	/**
	 * @return Array of DMTag objects
	 */
	public function getSearchResultsAsObjects() {
		$this->setNumResults(
				$this->getDataStore()->getTagsForQueryAsObjects($this, true));
		return $this->getDataStore()->getTagsForQueryAsObjects($this, false);
	}

	/**
	 * @return bool
	 */
	public final function isSortingByFrequency() {
		return $this->sort_by_frequency;
	}

	/**
	 * @param bool bool Whether to sort descending by frequency.
	 */
	public final function setSortByFrequency($bool) {
		$this->sort_by_frequency = (bool) $bool;
	}

	/**
	 * @return DMInternalURI URI of the query
	 */
	public function getURI() {
		$terms = $this->getPredicates();
		$collections = $this->getCollections();
		$objects = $this->getObjects();
		$query = array();
		for ($i = 0; $i < count($collections); $i++) {
			$query['alias' . $i] = $collections[$i]->getAlias();
		}
		for ($i = 0; $i < count($objects); $i++) {
			$query['objects' . $i] = sprintf("%s,%d",
					$objects[$i]->getCollection()->getAlias(),
					$objects[$i]->getPtr());
		}
		if ($this->getPage() > 1) {
			$query['page'] = $this->getPage();
		}
		if ($this->getLimit() != self::DEFAULT_LIMIT) {
			$query['rpp'] = $this->getLimit();
		}
		if (count($terms)) {
			$query['term'] = $terms[0];
		}
		if (!$this->isSortingByFrequency()) {
			$query['sort'] = "random";
		}

		return DMInternalURI::getURIWithParams("tags/search", $query);
	}

}
